package com.hospital.insurancepeople.client;

import com.hospital.api.RemoteEndesctryptionService;
import com.hospital.common.core.tioclient.WebsocketClient;
import com.hospital.insurancepeople.async.WxPayFunc;
import com.hospital.insurancepeople.module.mapper.InsuranceLogsMapper;
import com.hospital.insurancepeople.module.service.InsuranceLogsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.tio.client.ReconnConf;
import org.tio.websocket.client.WebSocket;
import org.tio.websocket.client.config.WsClientConfig;
import org.tio.websocket.common.WsPacket;

import javax.annotation.Resource;

@Slf4j
@Component
@RefreshScope
public class TioClient implements CommandLineRunner {
    @Value("${tiopresc.uri}")
    private String uri;
    @Value("${tiopresc.heartbeatTimeount}")
    private int heartbeatTimeount;
    @Value("${tiopresc.interval}")
    private int interval;
    @Value("${tiopresc.retryCount}")
    private int retryCount;
    @Resource
    private WxPayFunc wxPayFunc;
    @Resource
    private InsuranceLogsService insuranceLogsService;
    @Resource
    private RemoteEndesctryptionService remoteEndesctryptionService;

    @Resource
    private RestTemplate restTemplate;


    @Override
    public void run(String... args) throws Exception {
        try {
            WebsocketClient wsClient = WebsocketClient.create(uri, new WsClientConfig(
                    e -> log.info("=================================Tio-opened============================="),
                    e -> {
                        WsPacket data = e.data;
                        log.info("=================================Tio-data:\r\n" + e.data.toString());
                    },
                    e -> log.info("=================================Tio-close============================="),
                    e -> log.info("=================================Tio-close=============================" + e.msg),
                    Throwable::printStackTrace
            ));
            wsClient.init(heartbeatTimeount, new ReconnConf(interval, retryCount), new WebsocketClientHandler(wxPayFunc, insuranceLogsService, remoteEndesctryptionService,restTemplate));
            WebSocket ws = wsClient.connect();
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }
}
